package kbpost

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/logic/util"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetEntryFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetEntryFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetEntryFavoriteLogic {
	return &GetEntryFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetEntryFavoriteLogic) GetEntryFavorite(
	req *types.GetEntryFavoriteReq,
	headers *[]*types.Header,
) (resp *types.PerfumeCabinetListResp, err error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	// favPreload := "forumUserCollect:Id,ObjectId"
	// // 构造查询条件
	// var favFilters []string
	// favFilters = append(favFilters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	// favFilters = append(favFilters, "PlatformId,equalTo:"+strconv.FormatInt(int64(globalkey.ThirdPartyPlatformWechatMini), 10))
	// favFilters = append(favFilters, "ObjectType,equalTo:"+strconv.FormatInt(int64(globalkey.AttachmentLogTypeProduct), 10))
	// favFilters = append(favFilters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	// platformId := globalkey.ThirdPartyPlatformWechatMini

	// ret, err := l.svcCtx.ForumRpc.GetUserCollectList(l.ctx, &forumclient.BaseListReq{
	// 	Offset:     uint32((page - 1) * pageSize),
	// 	Limit:      uint32(pageSize),
	// 	Preload:    pointy.GetPointer(favPreload),
	// 	Filter:     pointy.GetPointer(strings.Join(favFilters, ";")),
	// 	VisitorId:  pointy.GetPointer(userId),
	// 	PlatformId: pointy.GetPointer(platformId),
	// })
	// if err != nil {
	// 	return nil, err
	// }

	preload := "blogBook:Id,Title,Slug;blogBookMeta:mediaId,mediaUrl;blogMedia:Uri,Url"
	preload += ";blogReactionLog:Id,PostId,PostType,Type,Count,CreatedAt"
	eagerLoad := "blogBook:blogBookMeta,blogMedia,blogReactionLog"
	var preFilters []string
	preFilters = append(preFilters, "UserId,equalTo:"+strconv.FormatUint(userId, 10))
	var reactionType string
	if req.Type != nil {
		reactionType = util.GetReactionType(*req.Type)
	} else {
		reactionType = util.GetReactionType(globalkey.ForumReactionTypeWant)
	}
	preFilters = append(preFilters, "Type,equalTo:"+reactionType)
	preFilterEntity := "blogReactionLog"
	var filters []string
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.PostStatusPublish), 10))

	res, err := l.svcCtx.BlogRpc.GetKBPostListTmp(l.ctx, &blogclient.BaseListReq{
		Offset:          uint32((page - 1) * pageSize),
		Limit:           uint32(pageSize),
		Preload:         pointy.GetPointer(preload),
		EagerLoad:       pointy.GetPointer(eagerLoad),
		Filter:          pointy.GetPointer(strings.Join(filters, ";")),
		PreFilterEntity: pointy.GetPointer(preFilterEntity),
		PreFilter:       pointy.GetPointer(strings.Join(preFilters, ";")),
		VisitorId:       pointy.GetPointer(userId),
		PlatformId:      pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.PerfumeCabinetListResp{
		BaseListInfo: types.BaseListInfo{
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			var mediaUrl *string
			var reviewCount *uint32
			if len(v.Meta) > 0 {
				for _, m := range v.Meta {
					if m.Key == nil || m.Value == nil {
						continue
					}

					val := *m.Value
					switch *m.Key {
					case "mediaUrl":
						mediaUrl = pointy.GetPointer(val)
					case "reviewCount":
						if i, err := strconv.ParseInt(val, 10, 32); err == nil {
							reviewCount = pointy.GetPointer(uint32(i))
						}
					}
				}
			}

			var reactionId *uint64
			var objectId *uint64
			var objectType *uint32
			var createdAt *string
			if v.ReactionLog != nil {
				reactionId = v.ReactionLog.Id
				objectId = v.ReactionLog.PostId
				objectType = v.ReactionLog.PostType
				createdAt = v.ReactionLog.CreatedAt
			}

			resp.List = append(resp.List, &types.PerfumeCabinetListInfo{
				Id:         reactionId,
				ObjectId:   objectId,
				ObjectType: objectType,
				CreatedAt:  createdAt,
				KBPost: &types.KbEntryInfo{
					Id:          v.Id,
					Title:       v.Title,
					Slug:        v.Slug,
					ImageUrl:    mediaUrl,
					ReviewCount: reviewCount,
				},
			})
		}
	}

	return resp, nil

	// if len(ret.List) > 0 {
	// 	var pids []string
	// 	for _, v := range ret.List {
	// 		if v.ObjectId != nil && *v.ObjectId > 0 {
	// 			pids = append(pids, strconv.FormatInt(int64(*v.ObjectId), 10))
	// 		}
	// 	}

	// preload := "product:Id,Title,Slug"
	// eagerLoad := "product:productMeta,productMedia,productRelationship"
	// preload += ";productMeta:mediaUrl,retailPriceMin,hotSell"
	// preload += ";productMedia:Uid,Url,altText,metaData"
	// preload += ";productRelationship:PerfumeId,PerfumeName,PerfumeSlug,BrandId,BrandName,BrandSlug"

	// var filters []string
	// filters = append(filters, "Id,in:"+strings.Join(pids, ","))
	// if req.Type != nil && *req.Type != globalkey.ProductTypePhysical {
	// 	filters = append(filters, "virtual,equalTo:"+strconv.FormatInt(int64(*req.Type), 10))
	// } else {
	// 	filters = append(filters, "virtual,equalTo:"+strconv.FormatInt(int64(globalkey.ProductTypePhysical), 10))
	// }
	// filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))

	// res, err := l.svcCtx.ProductRpc.GetProductList(l.ctx, &productclient.BaseListReq{
	// 	Preload:    pointy.GetPointer(preload),
	// 	EagerLoad:  pointy.GetPointer(eagerLoad),
	// 	Filter:     pointy.GetPointer(strings.Join(filters, ";")),
	// 	VisitorId:  pointy.GetPointer(userId),
	// 	PlatformId: pointy.GetPointer(platformId),
	// })
	// if err != nil {
	// 	return nil, err
	// }

	// if len(res.List) > 0 {
	// 	idProductMap := make(map[uint64]*types.GoodsInfo)
	// 	for _, v := range res.List {
	// 		if v.Id == nil || *v.Id == 0 {
	// 			continue
	// 		}

	// 		var retailPriceMin *string
	// 		var isNew *bool
	// 		var isHot *bool
	// 		var mediaUrl *string
	// 		if len(v.Meta) > 0 {
	// 			for _, m := range v.Meta {
	// 				if m.Key == nil || m.Value == nil {
	// 					continue
	// 				}

	// 				val := *m.Value
	// 				switch *m.Key {
	// 				case "retailPriceMin":
	// 					retailPriceMin = pointy.GetPointer(val)
	// 				case "isNew":
	// 					if val == "1" {
	// 						isNew = pointy.GetPointer(true)
	// 					}
	// 				case "isHot":
	// 					if val == "1" {
	// 						isHot = pointy.GetPointer(true)
	// 					}
	// 				case "hotSell":
	// 					if val == "1" {
	// 						isHot = pointy.GetPointer(true)
	// 					}
	// 				case "mediaUrl":
	// 					mediaUrl = pointy.GetPointer(val)
	// 				}
	// 			}
	// 		}

	// 		var brandTitle *string
	// 		if len(v.Relations) > 0 {
	// 			for _, m := range v.Relations {
	// 				if m.Key != nil {
	// 					switch *m.Key {
	// 					case globalkey.ProductRelationNameBrand:
	// 						brandTitle = m.Name
	// 					}
	// 				}
	// 			}
	// 		}

	// 		if len(v.Media) > 0 {
	// 			for _, m := range v.Media {
	// 				if mediaUrl != nil {
	// 					break
	// 				}

	// 				var url string
	// 				if m.Url != nil && len(*m.Url) > 0 {
	// 					url = *m.Url
	// 				}
	// 				if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
	// 					url = *m.Uri
	// 				}
	// 				mediaUrl = pointy.GetPointer(url)
	// 			}
	// 		}

	// 		var preTag *string
	// 		if isHot != nil && *isHot {
	// 			preTag = pointy.GetPointer("热卖")
	// 		} else if isNew != nil && *isNew {
	// 			preTag = pointy.GetPointer("新品")
	// 		}

	// 		idProductMap[*v.Id] = &types.GoodsInfo{
	// 			Id:       v.Id,
	// 			PreTag:   preTag,
	// 			Brand:    brandTitle,
	// 			Title:    v.Title,
	// 			Slug:     v.Slug,
	// 			MinPrice: retailPriceMin,
	// 			ImageUrl: mediaUrl,
	// 		}
	// 	}

	// 	for _, v := range ret.List {
	// 		if v.ObjectId != nil && *v.ObjectId > 0 {
	// 			if goods, ok := idProductMap[*v.ObjectId]; ok {
	// 				goods.Uid = v.Id
	// 				resp.List = append(resp.List, goods)
	// 			}
	// 		}
	// 	}
	// }
	// }

	// *headers = []*types.Header{
	// 	{
	// 		Key:   "x-class",
	// 		Value: "com.djx.appview.GoodsFavPage",
	// 	},
	// }

	return resp, nil
}
